import React from 'react'
import { useNavigate } from 'react-router-dom'
import { LockOutlined, UserOutlined } from '@ant-design/icons'
import { Button, Form, Input, message } from 'antd'
import './login.css'
import { SYSTEMNAME } from '../../redux/constant'
import { getLoginUserByName } from '../../utils/request/get.js'
import { createToken } from '../../redux/actions/Token'
import { useDispatch, useSelector } from 'react-redux'
import { refresh } from '../../utils/common'

export default function Login() {
	const navigate = useNavigate()
	const dispatch = useDispatch()
	const token = useSelector(state => state.TokenReducer.token)

	const setToken = (user) => {
		const { roleId, username, id, userId } = user
		var value = { roleId, username, id, userId }
		dispatch(createToken(value))
	}

	const onFinish = (value) => {
		const { username, password } = value
		getLoginUserByName(username).then(res => {
			// console.log(res);
			const data = res.data.loginUsers
			if (data.length === 0) {
				message.warning('查无此人')
				return
			}
			for (let i = 0; i < data.length; i++) {
				const user = data[i];
				if (!user.User.roleState) {
					message.error("该用户被禁用")
					return
				}
				if (password === user.password) {
					setToken(user)
					setTimeout(() => {
						if (token) {
							navigate('/home')
							refresh()
						}
					}, 500)
					console.log("login success");
					return
				}
			}
			message.error("账号或密码输入错误")
		})

	}

	return (
		<div style={{ height: '100%' }} className='login'>
			<div className="loginContainer">
				<div className="title">{SYSTEMNAME}</div>
				<Form
					name="normal_login"
					className="login-form"
					initialValues={{
						remember: true,
					}}
					onFinish={onFinish}
				>
					<Form.Item
						name="username"
						rules={[
							{
								required: true,
								message: '请输入用户名!',
							},
						]}
					>
						<Input
							prefix={<UserOutlined className="site-form-item-icon" />}
							placeholder="请输入用户名" />
					</Form.Item>
					<Form.Item
						name="password"
						rules={[
							{
								required: true,
								message: '请输入密码!',
							},
						]}
					>
						<Input.Password
							prefix={<LockOutlined className="site-form-item-icon" />}
							placeholder="请输入密码" />
					</Form.Item>
					<Form.Item>
						<Button type="primary" block htmlType="submit" className="login-form-button">登录
						</Button>
					</Form.Item>
				</Form>
			</div>
		</div>
	)
}